<?php

namespace common\helpers;

use http\Params;
use Yii;
use OSS\OssClient;
use OSS\Core\OssException;

class OssHelper
{
    /**
     * accessKeyId
     *
     * @var
     */
    protected $accessKeyId;

    /**
     * accessSecret
     *
     * @var
     */
    protected $accessSecret;

    /**
     * bucket【存储空间名称】
     *
     * @var
     */
    protected $bucket;

    /**
     * endPoint【https://help.aliyun.com/document_detail/31837.html】
     *
     * @var
     */
    protected $endPoint;

    /**
     * @var
     */
    protected $ossClient;

    /**
     * OssHelper constructor.
     * @param string $accessKeyId
     * @param string $accessSecret
     * @param string $bucket
     * @param string $endPoint
     * @throws OssException
     */
    public function __construct(string $accessKeyId = '', string $accessSecret = '', string $bucket = '', string $endPoint = '')
    {
        $this->accessKeyId = $accessKeyId ? $accessKeyId : Yii::$app->params['aliyunAccessKeyId'];
        $this->accessSecret = $accessSecret ? $accessSecret : Yii::$app->params['aliyunAccessSecret'];
        $this->bucket = $bucket ? $bucket : Yii::$app->params['aliyunBucket'];
        $this->endPoint = $endPoint ? $endPoint : Yii::$app->params['aliyunEndPoint'];

        $this->ossClient = new OssClient($this->accessKeyId, $this->accessSecret, $this->endPoint);
    }

    /**
     * 创建存储空间
     *
     * @param string $bucket 存储空间名称
     * @param string $type 权限类型【私有、公共读、公共读写】
     * @param array|null $options 存储类型【标准、低频访问、归档】
     * @return mixed|null
     */
    public function createBucket(string $bucket, $type = OssClient::OSS_ACL_TYPE_PRIVATE, array $options = null)
    {
        /*$options = [
            OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_IA
        ];*/
        return $this->ossClient->createBucket($bucket, $type, $options);
    }

    /**
     * 上传文件
     *
     *  Demo:
     *  // upload file
     *  $uploadFilePath = Yii::$app->params['upload_dir'].'/hfx.jpeg';
     *  // create filename
     *  $fileName = ImageHelper::createFileName('jpeg');
     *  // get redis project
     *  $project = RedisHelper::getProjectById($projectId);
     *  // save file name
     *  $saveFileName = "{$project['name_sx']}/{$fileName}";
     *  // upload
     *  $ossHelper = new OssHelper();
     *  $res = $ossHelper->upload($uploadFilePath, $saveFileName);
     *  print_r($res);
     *
     * @param string $uploadFilePath 上传文件【包含路径】
     * @param string $saveFileName 上传保存的文件名【demo: dir/test.jpg】
     * @return mixed|null
     */
    public function upload(string $uploadFilePath = '', string $saveFileName = '')
    {
        return $this->ossClient->uploadFile($this->bucket, $saveFileName, $uploadFilePath);
    }

    /**
     * 上传缩略图
     *
     * @param string $uploadFilePath
     * @param string $saveFileName
     * @return string
     * @throws OssException
     * @author chenyuebin
     */
    public function uploadThumbnail(string $uploadFilePath = '', string $saveFileName = '')
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $uploadFilePath,
            OssClient::OSS_PROCESS => "image/resize,m_mfit,h_160,w_256,color_FFFFFF"
        );
        return $this->ossClient->getObject($this->bucket, $saveFileName, $options);
    }

    /**
     * 下载文件到本地
     *
     * @param string $downFileName 下载文件名【demo: dir/test.jpg】
     * @param string $saveFile 保存文件名
     * @return mixed|string
     */
    public function download(string $downFileName = '', string $saveFile = '', int $projectId = 0, int $isThumb = 0)
    {
        $project = RedisHelper::getProjectById($projectId);
        if ($project) {
            $saveFile = "{$project['name_sx']}/{$saveFile}";
            $downFileName = "{$project['name_sx']}/{$downFileName}";
        }

        // 完整路径
        $saveFileName = Yii::$app->params['upload_dir'] . "/{$saveFile}";

        // 文件路径是否存在
        if ($num = strrpos($saveFileName, '/')) {
            $saveFilePath = substr($saveFileName, 0, $num);
            FileHelper::createDirectory($saveFilePath);
        }

        // 下载到本地
        $options = [
            OssClient::OSS_FILE_DOWNLOAD => $saveFileName
        ];
        $isThumb && $options[OssClient::OSS_PROCESS] = 'image/resize,m_fixed,h_160,w_256';
        $this->ossClient->getObject($this->bucket, $downFileName, $options);

        return [
            'file' => $saveFile,
            'file_url' => ImageHelper::getOssImageUrl($saveFile),
        ];
    }

    // 删除图片 先测试列举
    public function deleteImage($objects)
    {
        try {
            $result = $this->ossClient->deleteObjects($this->bucket,$objects);
            foreach ($result as $info){
                $obj = strval($info);
                printf("Delete ".$obj." : Success" . "\n");
            }
            printf("Delete Objects : OK" . "\n");
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

}
